#include "../source/server.hpp"

#include <cstdlib>

std::unordered_map<uint64_t,ConnectionPtr> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;
LoopThreadPool* pool;

void OnConnected(const ConnectionPtr& conn)
{
    lg(Info,"NEW CONNECTION: %p, id:%d", conn.get(), conn->Id());
}

void OnMessage(const ConnectionPtr& conn, Buffer* buf)
{
    lg(Info,"server get message:%s", buf->ReadPosition());
    buf->MoveReaderOffset(buf->ReadAbleSize());
    std::string reply("Hello Client!");
    conn->Send(reply.c_str(), reply.size());
}

void DestroyConntection(const ConnectionPtr& conn)
{
    lg(Info, "connection id:%d destroied.", conn->Id());
    _conns.erase(conn->Id());
}

void NewConntion(int fd)
{
    ++conn_id;
    ConnectionPtr conn(new Connection(pool->NextLoop(), conn_id, fd));
    conn->SetConnectedCallback(std::bind(&OnConnected, std::placeholders::_1));
    conn->SetMessageCallback(std::bind(&OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSvrClosedCallback(std::bind(&DestroyConntection, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();
    _conns[conn_id] = conn;
    lg(Debug, "a new cilent connected.");
}

int main()
{
    pool = new LoopThreadPool(&base_loop);
    pool->SetThreadcount(2);
    pool->Create();
    Acceptor acceptor(&base_loop, 8888);
    acceptor.SetAcceptCallback(std::bind(&NewConntion, std::placeholders::_1));
    acceptor.Listen();

    base_loop.Start();

    return 0;
}